package main

import (
    "bytes"
    "strings"
    "net"
)

type IpRange struct {
    IPStart net.IP
    IPEnd   net.IP
}

type IpAcl struct {
    Range []IpRange
}

func (acl *IpAcl) isAllow(ipStr string) bool {
    if len(acl.Range) == 0 {
        return true
    }
    
    ip := net.ParseIP(ipStr)
    if ip == nil {
        return false
    }
    
    ip = ip.To16()
    for _, r := range acl.Range {
        if bytes.Compare(ip, r.IPStart) >= 0 && bytes.Compare(ip, r.IPEnd) <= 0 {
            return true
        }
    }
    
    return false
}

func parseIpAcl(str string) *IpAcl {
    acl := &IpAcl{}
    acl.Range = make([]IpRange, 0)
    
    elms := strings.Split(str, ",")
    for _, e := range elms {
        ip := strings.Split(e, "-")
        if len(ip) != 2 {
            continue
        }
        ips := net.ParseIP(ip[0])
        ipe := net.ParseIP(ip[1])
        if ips != nil && ipe != nil {
            ips = ips.To16()
            ipe = ipe.To16()
            acl.Range = append(acl.Range, IpRange{IPStart:ips, IPEnd:ipe})
        }
    }
    
    return acl
}